很常寫 Java 或是 Kotlin 的朋友對 annotation 大概不陌生,它其實就是在程式碼裡面做標記,而這個標記做什麼或者背後隱含什麼意義,都是看處理這個 annotation 的地方。
下面的程式碼就是 annotation 的範例,帶有 @ 前綴的標示就是 Annotation 的開始。
@RssTag(name = "channel")
Annotation 可以標註在 class 、function 、 variable 或是 value 等元素上面,像下面範例就是對 class 和 value 標註 annotation。Annotation 也可以帶一些自定義的資料進去,比方說像是 @RssTag 後面就多帶了 name 和 order 的屬性,他的型別也可以是 String 、 Int 或  Array 之類的。
@RssTag(name = "channel")
data class MyChannel(
    val title: String?,
    @RssTag(name = "author", order = [OrderType.ITUNES, OrderType.RSS_STANDARD])
    val name: String?,
): Serializable
那這樣的標註可以幫我們做什麼事?像上面的範例裡,其實我們就是在表達下方的 RSS tag 結構。
<channel>
    <title>the title</title>
    <author>the author</author>
    <itunes:author>itunes author</itunes:author>
</channel>
所以我們把 MyChannel 定義成 <channel> tag 的結構,底下包含了三個 tag ,而只打算取兩個值:
<title> 取值放到 MyChannel 的 title 裡<author> 和 <iTunes:author> 取值,依照 order 裡面定義的順序陣列取值,先取 <iTunes:author> ,沒有的話再取  <author> ,分別對應 @RssTag 裡面的 order 定義: OrderType.ITUNES 和 OrderType.RSS_STANDARD 。這樣我們就使用了 annotation 標註了我們客製的資料格式,annotation 幫助我們去對不同的資料樣子去做對應,而我們的之後要講解的 annotation processor 就是要利用 annotation 這一層對應關係,去產生出我們自己客製化的 data parser 。